//
//  YSPMainTabBar.swift
//  Weibo Demo
//
//  Created by 朴裕识 on 15/12/16.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit

class YSPMainTabBar: UITabBar {
    
    //让控制器传个闭包过来，闭包里面为撰写按钮被点击时要执行的内容
    var composeClosure: (() -> Void)?

    let tabBarCount = 5///<属性：5个子控件
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundImage = UIImage(named: "tabbar_background")
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //计算每个tab的宽度
        let width = self.bounds.width / CGFloat(tabBarCount)
        
        //设置一个原始frame，方便后面用cgrectOffset
        let originalFrame = CGRect(x: 0, y: 0, width: width, height: self.bounds.height)
        
        //遍历布局子空间
        var index = 0
        for view in self.subviews {
         
            if view is UIControl && !(view is UIButton) {
                view.frame = CGRectOffset(originalFrame, CGFloat(index) * width, 0)
                
                index += index == 1 ? 2 : 1
//                index ++
//                if index == 2 {
//                    index ++
//                }
            }

        }///<遍历结束
        
        composeBtn.frame = CGRectOffset(originalFrame, 2.0 * width, 0)
    }
    
    lazy var composeBtn: UIButton = {
        let btn = UIButton()
        
        //设置图片
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Selected)
        
        //设置背景图片
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Selected)
        
        //添加到父控件
        self.addSubview(btn)
        
        //添加点击事件
        btn.addTarget(self, action: "composeBtnDidClicked", forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
    
    @objc private func composeBtnDidClicked() {
        composeClosure?()
    }
}
